package shuai.test;

import java.util.Iterator;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.ManyToOne;
import org.hibernate.mapping.OneToMany;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import shuai.model.Course;
import shuai.model.Jd;
import shuai.model.Qx;
import shuai.model.Student;

public class Demo {
	Session session=null;
	@Before
	public void initSession(){
		Configuration configuration=new Configuration().configure();
		SessionFactory factory=configuration.buildSessionFactory();
		session=factory.openSession();
	}
	@Test
	public void add(){
		Transaction transaction=session.beginTransaction();
		Qx qx=new Qx("金水区");
		session.save(qx);
		Jd jd1=new Jd("金水路",qx);
		Jd jd2=new Jd("文化节",qx);
		session.save(jd1);
		session.save(jd2);
		transaction.commit();
	}
	@Test
	public void ManyToOne(){
		Jd jd=(Jd) session.get(Jd.class, 2);
		System.out.println(jd.getJdName()+"所在的街道是：");
		System.out.println(jd.getQx().getQxname());
	}
	@Test
	public void OneToMany(){
		Qx qx=(Qx) session.get(Qx.class, 1);
		System.out.println(qx.getQxname()+"下面的街道有：");
		Iterator<Jd> jds=qx.getJds().iterator();
		while(jds.hasNext()){
			System.out.print(jds.next().getJdName());
		}
	}
	@Test
	public void AddManyAddOne(){
		Transaction transaction=session.beginTransaction();
		Jd jd1=new Jd("九如路");
		Jd jd2=new Jd("东风南路");
		Jd jd3=new Jd("季成璐");
		session.save(jd1);
		session.save(jd2);
		session.save(jd3);
		Qx qx=new Qx("郑东新区");
		qx.getJds().add(jd1);
		qx.getJds().add(jd2);
		qx.getJds().add(jd3);
		session.save(qx);
		transaction.commit();
	}
	@Test
	public void delMany(){
		Transaction transaction=session.beginTransaction();
		Qx qx=(Qx) session.get(Qx.class, 10);
		Jd jd=(Jd) session.get(Jd.class, 25);
		//先删除set中的对象
		qx.getJds().remove(jd);
		//删除数据库中的记录
		session.delete(jd);
		transaction.commit();
	}
	@Test
	public void delOne(){
		Transaction transaction=session.beginTransaction();
		Qx qx=(Qx) session.get(Qx.class, 9);
		session.delete(qx);
		transaction.commit();
	}
	@Test
	public void ManyToMany(){
		Transaction transaction=session.beginTransaction();
		Course course1=new Course("java");
		Course course2=new Course("php");
		session.save(course1);
		session.save(course2);
		Student stu1=new Student("kong");
		Student stu2=new Student("shuai");
		stu1.getCourses().add(course1);
		stu1.getCourses().add(course2);
		stu2.getCourses().add(course1);
		stu2.getCourses().add(course2);
		session.save(stu1);
		session.save(stu2);
		transaction.commit();
	}
	
	@After
	public void destorySession(){
		session.close();
	}
}
